package util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    public BaseServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            {
        try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        this.request = request;
        this.response = response;
        doBusiness();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
             {
        try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        this.request = request;
        this.response = response;
        doBusiness();
    }

    public void init()   {
    }

    public void forward(String url) {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
        
        try {
            rd.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void redirect(String url) {
    	  String path = request.getContextPath(); 
		   
	    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
	    	
	    	try {
				response.sendRedirect(basePath+url);
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    protected abstract void doBusiness();
}
